/**
 * 多语言错误消息
 * 支持多种语言的错误提示信息
 */

import { LanguageType, SUPPORTED_LANGUAGES } from '../config/languages';

// 错误消息类型
export interface ErrorMessage {
  code: number;
  messages: Record<LanguageType, string>;
}

// 通用错误消息
export const COMMON_ERROR_MESSAGES: ErrorMessage[] = [
  {
    code: 200,
    messages: {
      [SUPPORTED_LANGUAGES.ZH_CN]: '操作成功',
      [SUPPORTED_LANGUAGES.ZH_TW]: '操作成功',
      [SUPPORTED_LANGUAGES.EN_US]: 'Operation successful',
      [SUPPORTED_LANGUAGES.JA_JP]: '操作が成功しました',
      [SUPPORTED_LANGUAGES.KO_KR]: '작업이 성공했습니다',
      [SUPPORTED_LANGUAGES.FR_FR]: 'Opération réussie',
      [SUPPORTED_LANGUAGES.DE_DE]: 'Operation erfolgreich',
      [SUPPORTED_LANGUAGES.ES_ES]: 'Operación exitosa',
      [SUPPORTED_LANGUAGES.PT_BR]: 'Operação bem-sucedida',
      [SUPPORTED_LANGUAGES.RU_RU]: 'Операция выполнена успешно'
    }
  },
  {
    code: 400,
    messages: {
      [SUPPORTED_LANGUAGES.ZH_CN]: '请求参数错误',
      [SUPPORTED_LANGUAGES.ZH_TW]: '請求參數錯誤',
      [SUPPORTED_LANGUAGES.EN_US]: 'Bad request',
      [SUPPORTED_LANGUAGES.JA_JP]: 'リクエストが不正です',
      [SUPPORTED_LANGUAGES.KO_KR]: '잘못된 요청입니다',
      [SUPPORTED_LANGUAGES.FR_FR]: 'Requête incorrecte',
      [SUPPORTED_LANGUAGES.DE_DE]: 'Ungültige Anfrage',
      [SUPPORTED_LANGUAGES.ES_ES]: 'Solicitud incorrecta',
      [SUPPORTED_LANGUAGES.PT_BR]: 'Solicitação inválida',
      [SUPPORTED_LANGUAGES.RU_RU]: 'Неверный запрос'
    }
  },
  {
    code: 401,
    messages: {
      [SUPPORTED_LANGUAGES.ZH_CN]: '未授权访问',
      [SUPPORTED_LANGUAGES.ZH_TW]: '未授權訪問',
      [SUPPORTED_LANGUAGES.EN_US]: 'Unauthorized access',
      [SUPPORTED_LANGUAGES.JA_JP]: '認証が必要です',
      [SUPPORTED_LANGUAGES.KO_KR]: '인증이 필요합니다',
      [SUPPORTED_LANGUAGES.FR_FR]: 'Accès non autorisé',
      [SUPPORTED_LANGUAGES.DE_DE]: 'Nicht autorisierter Zugriff',
      [SUPPORTED_LANGUAGES.ES_ES]: 'Acceso no autorizado',
      [SUPPORTED_LANGUAGES.PT_BR]: 'Acesso não autorizado',
      [SUPPORTED_LANGUAGES.RU_RU]: 'Неавторизованный доступ'
    }
  },
  {
    code: 403,
    messages: {
      [SUPPORTED_LANGUAGES.ZH_CN]: '禁止访问',
      [SUPPORTED_LANGUAGES.ZH_TW]: '禁止訪問',
      [SUPPORTED_LANGUAGES.EN_US]: 'Access forbidden',
      [SUPPORTED_LANGUAGES.JA_JP]: 'アクセスが禁止されています',
      [SUPPORTED_LANGUAGES.KO_KR]: '접근이 금지되었습니다',
      [SUPPORTED_LANGUAGES.FR_FR]: 'Accès interdit',
      [SUPPORTED_LANGUAGES.DE_DE]: 'Zugriff verboten',
      [SUPPORTED_LANGUAGES.ES_ES]: 'Acceso prohibido',
      [SUPPORTED_LANGUAGES.PT_BR]: 'Acesso proibido',
      [SUPPORTED_LANGUAGES.RU_RU]: 'Доступ запрещен'
    }
  },
  {
    code: 404,
    messages: {
      [SUPPORTED_LANGUAGES.ZH_CN]: '资源不存在',
      [SUPPORTED_LANGUAGES.ZH_TW]: '資源不存在',
      [SUPPORTED_LANGUAGES.EN_US]: 'Resource not found',
      [SUPPORTED_LANGUAGES.JA_JP]: 'リソースが見つかりません',
      [SUPPORTED_LANGUAGES.KO_KR]: '리소스를 찾을 수 없습니다',
      [SUPPORTED_LANGUAGES.FR_FR]: 'Ressource introuvable',
      [SUPPORTED_LANGUAGES.DE_DE]: 'Ressource nicht gefunden',
      [SUPPORTED_LANGUAGES.ES_ES]: 'Recurso no encontrado',
      [SUPPORTED_LANGUAGES.PT_BR]: 'Recurso não encontrado',
      [SUPPORTED_LANGUAGES.RU_RU]: 'Ресурс не найден'
    }
  },
  {
    code: 500,
    messages: {
      [SUPPORTED_LANGUAGES.ZH_CN]: '服务器内部错误',
      [SUPPORTED_LANGUAGES.ZH_TW]: '伺服器內部錯誤',
      [SUPPORTED_LANGUAGES.EN_US]: 'Internal server error',
      [SUPPORTED_LANGUAGES.JA_JP]: 'サーバー内部エラー',
      [SUPPORTED_LANGUAGES.KO_KR]: '서버 내부 오류',
      [SUPPORTED_LANGUAGES.FR_FR]: 'Erreur interne du serveur',
      [SUPPORTED_LANGUAGES.DE_DE]: 'Interner Serverfehler',
      [SUPPORTED_LANGUAGES.ES_ES]: 'Error interno del servidor',
      [SUPPORTED_LANGUAGES.PT_BR]: 'Erro interno do servidor',
      [SUPPORTED_LANGUAGES.RU_RU]: 'Внутренняя ошибка сервера'
    }
  }
];

// 业务错误消息
export const BUSINESS_ERROR_MESSAGES: ErrorMessage[] = [
  {
    code: 1000,
    messages: {
      [SUPPORTED_LANGUAGES.ZH_CN]: '用户不存在',
      [SUPPORTED_LANGUAGES.ZH_TW]: '用戶不存在',
      [SUPPORTED_LANGUAGES.EN_US]: 'User not found',
      [SUPPORTED_LANGUAGES.JA_JP]: 'ユーザーが見つかりません',
      [SUPPORTED_LANGUAGES.KO_KR]: '사용자를 찾을 수 없습니다',
      [SUPPORTED_LANGUAGES.FR_FR]: 'Utilisateur introuvable',
      [SUPPORTED_LANGUAGES.DE_DE]: 'Benutzer nicht gefunden',
      [SUPPORTED_LANGUAGES.ES_ES]: 'Usuario no encontrado',
      [SUPPORTED_LANGUAGES.PT_BR]: 'Usuário não encontrado',
      [SUPPORTED_LANGUAGES.RU_RU]: 'Пользователь не найден'
    }
  },
  {
    code: 1001,
    messages: {
      [SUPPORTED_LANGUAGES.ZH_CN]: '用户已存在',
      [SUPPORTED_LANGUAGES.ZH_TW]: '用戶已存在',
      [SUPPORTED_LANGUAGES.EN_US]: 'User already exists',
      [SUPPORTED_LANGUAGES.JA_JP]: 'ユーザーは既に存在します',
      [SUPPORTED_LANGUAGES.KO_KR]: '사용자가 이미 존재합니다',
      [SUPPORTED_LANGUAGES.FR_FR]: 'L\'utilisateur existe déjà',
      [SUPPORTED_LANGUAGES.DE_DE]: 'Benutzer existiert bereits',
      [SUPPORTED_LANGUAGES.ES_ES]: 'El usuario ya existe',
      [SUPPORTED_LANGUAGES.PT_BR]: 'Usuário já existe',
      [SUPPORTED_LANGUAGES.RU_RU]: 'Пользователь уже существует'
    }
  },
  {
    code: 1002,
    messages: {
      [SUPPORTED_LANGUAGES.ZH_CN]: '用户已被禁用',
      [SUPPORTED_LANGUAGES.ZH_TW]: '用戶已被禁用',
      [SUPPORTED_LANGUAGES.EN_US]: 'User is disabled',
      [SUPPORTED_LANGUAGES.JA_JP]: 'ユーザーは無効になっています',
      [SUPPORTED_LANGUAGES.KO_KR]: '사용자가 비활성화되었습니다',
      [SUPPORTED_LANGUAGES.FR_FR]: 'L\'utilisateur est désactivé',
      [SUPPORTED_LANGUAGES.DE_DE]: 'Benutzer ist deaktiviert',
      [SUPPORTED_LANGUAGES.ES_ES]: 'El usuario está deshabilitado',
      [SUPPORTED_LANGUAGES.PT_BR]: 'Usuário está desabilitado',
      [SUPPORTED_LANGUAGES.RU_RU]: 'Пользователь отключен'
    }
  },
  {
    code: 1004,
    messages: {
      [SUPPORTED_LANGUAGES.ZH_CN]: '密码错误',
      [SUPPORTED_LANGUAGES.ZH_TW]: '密碼錯誤',
      [SUPPORTED_LANGUAGES.EN_US]: 'Incorrect password',
      [SUPPORTED_LANGUAGES.JA_JP]: 'パスワードが間違っています',
      [SUPPORTED_LANGUAGES.KO_KR]: '비밀번호가 잘못되었습니다',
      [SUPPORTED_LANGUAGES.FR_FR]: 'Mot de passe incorrect',
      [SUPPORTED_LANGUAGES.DE_DE]: 'Falsches Passwort',
      [SUPPORTED_LANGUAGES.ES_ES]: 'Contraseña incorrecta',
      [SUPPORTED_LANGUAGES.PT_BR]: 'Senha incorreta',
      [SUPPORTED_LANGUAGES.RU_RU]: 'Неверный пароль'
    }
  },
  {
    code: 1007,
    messages: {
      [SUPPORTED_LANGUAGES.ZH_CN]: '登录失败',
      [SUPPORTED_LANGUAGES.ZH_TW]: '登錄失敗',
      [SUPPORTED_LANGUAGES.EN_US]: 'Login failed',
      [SUPPORTED_LANGUAGES.JA_JP]: 'ログインに失敗しました',
      [SUPPORTED_LANGUAGES.KO_KR]: '로그인에 실패했습니다',
      [SUPPORTED_LANGUAGES.FR_FR]: 'Échec de la connexion',
      [SUPPORTED_LANGUAGES.DE_DE]: 'Anmeldung fehlgeschlagen',
      [SUPPORTED_LANGUAGES.ES_ES]: 'Error de inicio de sesión',
      [SUPPORTED_LANGUAGES.PT_BR]: 'Falha no login',
      [SUPPORTED_LANGUAGES.RU_RU]: 'Ошибка входа'
    }
  }
];

// 认证错误消息
export const AUTH_ERROR_MESSAGES: ErrorMessage[] = [
  {
    code: 2000,
    messages: {
      [SUPPORTED_LANGUAGES.ZH_CN]: '访问令牌缺失',
      [SUPPORTED_LANGUAGES.ZH_TW]: '訪問令牌缺失',
      [SUPPORTED_LANGUAGES.EN_US]: 'Access token missing',
      [SUPPORTED_LANGUAGES.JA_JP]: 'アクセストークンが不足しています',
      [SUPPORTED_LANGUAGES.KO_KR]: '액세스 토큰이 누락되었습니다',
      [SUPPORTED_LANGUAGES.FR_FR]: 'Jeton d\'accès manquant',
      [SUPPORTED_LANGUAGES.DE_DE]: 'Zugriffstoken fehlt',
      [SUPPORTED_LANGUAGES.ES_ES]: 'Token de acceso faltante',
      [SUPPORTED_LANGUAGES.PT_BR]: 'Token de acesso ausente',
      [SUPPORTED_LANGUAGES.RU_RU]: 'Отсутствует токен доступа'
    }
  },
  {
    code: 2001,
    messages: {
      [SUPPORTED_LANGUAGES.ZH_CN]: '访问令牌无效',
      [SUPPORTED_LANGUAGES.ZH_TW]: '訪問令牌無效',
      [SUPPORTED_LANGUAGES.EN_US]: 'Invalid access token',
      [SUPPORTED_LANGUAGES.JA_JP]: '無効なアクセストークン',
      [SUPPORTED_LANGUAGES.KO_KR]: '유효하지 않은 액세스 토큰',
      [SUPPORTED_LANGUAGES.FR_FR]: 'Jeton d\'accès invalide',
      [SUPPORTED_LANGUAGES.DE_DE]: 'Ungültiger Zugriffstoken',
      [SUPPORTED_LANGUAGES.ES_ES]: 'Token de acceso inválido',
      [SUPPORTED_LANGUAGES.PT_BR]: 'Token de acesso inválido',
      [SUPPORTED_LANGUAGES.RU_RU]: 'Недействительный токен доступа'
    }
  },
  {
    code: 2002,
    messages: {
      [SUPPORTED_LANGUAGES.ZH_CN]: '访问令牌已过期',
      [SUPPORTED_LANGUAGES.ZH_TW]: '訪問令牌已過期',
      [SUPPORTED_LANGUAGES.EN_US]: 'Access token expired',
      [SUPPORTED_LANGUAGES.JA_JP]: 'アクセストークンの有効期限が切れています',
      [SUPPORTED_LANGUAGES.KO_KR]: '액세스 토큰이 만료되었습니다',
      [SUPPORTED_LANGUAGES.FR_FR]: 'Jeton d\'accès expiré',
      [SUPPORTED_LANGUAGES.DE_DE]: 'Zugriffstoken abgelaufen',
      [SUPPORTED_LANGUAGES.ES_ES]: 'Token de acceso expirado',
      [SUPPORTED_LANGUAGES.PT_BR]: 'Token de acesso expirado',
      [SUPPORTED_LANGUAGES.RU_RU]: 'Срок действия токена доступа истек'
    }
  }
];

// 验证错误消息
export const VALIDATION_ERROR_MESSAGES: ErrorMessage[] = [
  {
    code: 3000,
    messages: {
      [SUPPORTED_LANGUAGES.ZH_CN]: '必填字段缺失',
      [SUPPORTED_LANGUAGES.ZH_TW]: '必填欄位缺失',
      [SUPPORTED_LANGUAGES.EN_US]: 'Required field missing',
      [SUPPORTED_LANGUAGES.JA_JP]: '必須フィールドが不足しています',
      [SUPPORTED_LANGUAGES.KO_KR]: '필수 필드가 누락되었습니다',
      [SUPPORTED_LANGUAGES.FR_FR]: 'Champ requis manquant',
      [SUPPORTED_LANGUAGES.DE_DE]: 'Pflichtfeld fehlt',
      [SUPPORTED_LANGUAGES.ES_ES]: 'Campo requerido faltante',
      [SUPPORTED_LANGUAGES.PT_BR]: 'Campo obrigatório ausente',
      [SUPPORTED_LANGUAGES.RU_RU]: 'Отсутствует обязательное поле'
    }
  },
  {
    code: 3001,
    messages: {
      [SUPPORTED_LANGUAGES.ZH_CN]: '字段类型错误',
      [SUPPORTED_LANGUAGES.ZH_TW]: '欄位類型錯誤',
      [SUPPORTED_LANGUAGES.EN_US]: 'Field type error',
      [SUPPORTED_LANGUAGES.JA_JP]: 'フィールドタイプエラー',
      [SUPPORTED_LANGUAGES.KO_KR]: '필드 타입 오류',
      [SUPPORTED_LANGUAGES.FR_FR]: 'Erreur de type de champ',
      [SUPPORTED_LANGUAGES.DE_DE]: 'Feldtypfehler',
      [SUPPORTED_LANGUAGES.ES_ES]: 'Error de tipo de campo',
      [SUPPORTED_LANGUAGES.PT_BR]: 'Erro de tipo de campo',
      [SUPPORTED_LANGUAGES.RU_RU]: 'Ошибка типа поля'
    }
  }
];

// 数据库错误消息
export const DATABASE_ERROR_MESSAGES: ErrorMessage[] = [
  {
    code: 4000,
    messages: {
      [SUPPORTED_LANGUAGES.ZH_CN]: '数据库连接失败',
      [SUPPORTED_LANGUAGES.ZH_TW]: '資料庫連接失敗',
      [SUPPORTED_LANGUAGES.EN_US]: 'Database connection failed',
      [SUPPORTED_LANGUAGES.JA_JP]: 'データベース接続に失敗しました',
      [SUPPORTED_LANGUAGES.KO_KR]: '데이터베이스 연결에 실패했습니다',
      [SUPPORTED_LANGUAGES.FR_FR]: 'Échec de la connexion à la base de données',
      [SUPPORTED_LANGUAGES.DE_DE]: 'Datenbankverbindung fehlgeschlagen',
      [SUPPORTED_LANGUAGES.ES_ES]: 'Error de conexión a la base de datos',
      [SUPPORTED_LANGUAGES.PT_BR]: 'Falha na conexão com o banco de dados',
      [SUPPORTED_LANGUAGES.RU_RU]: 'Ошибка подключения к базе данных'
    }
  },
  {
    code: 4300,
    messages: {
      [SUPPORTED_LANGUAGES.ZH_CN]: '唯一约束违反',
      [SUPPORTED_LANGUAGES.ZH_TW]: '唯一約束違反',
      [SUPPORTED_LANGUAGES.EN_US]: 'Unique constraint violation',
      [SUPPORTED_LANGUAGES.JA_JP]: '一意制約違反',
      [SUPPORTED_LANGUAGES.KO_KR]: '고유 제약 조건 위반',
      [SUPPORTED_LANGUAGES.FR_FR]: 'Violation de contrainte unique',
      [SUPPORTED_LANGUAGES.DE_DE]: 'Verletzung der eindeutigen Einschränkung',
      [SUPPORTED_LANGUAGES.ES_ES]: 'Violación de restricción única',
      [SUPPORTED_LANGUAGES.PT_BR]: 'Violação de restrição única',
      [SUPPORTED_LANGUAGES.RU_RU]: 'Нарушение уникального ограничения'
    }
  },
  {
    code: 4301,
    messages: {
      [SUPPORTED_LANGUAGES.ZH_CN]: '外键约束违反',
      [SUPPORTED_LANGUAGES.ZH_TW]: '外鍵約束違反',
      [SUPPORTED_LANGUAGES.EN_US]: 'Foreign key constraint violation',
      [SUPPORTED_LANGUAGES.JA_JP]: '外部キー制約違反',
      [SUPPORTED_LANGUAGES.KO_KR]: '외래 키 제약 조건 위반',
      [SUPPORTED_LANGUAGES.FR_FR]: 'Violation de contrainte de clé étrangère',
      [SUPPORTED_LANGUAGES.DE_DE]: 'Verletzung der Fremdschlüsseleinschränkung',
      [SUPPORTED_LANGUAGES.ES_ES]: 'Violación de restricción de clave foránea',
      [SUPPORTED_LANGUAGES.PT_BR]: 'Violação de restrição de chave estrangeira',
      [SUPPORTED_LANGUAGES.RU_RU]: 'Нарушение ограничения внешнего ключа'
    }
  }
];

// 合并所有错误消息
export const ALL_ERROR_MESSAGES: ErrorMessage[] = [
  ...COMMON_ERROR_MESSAGES,
  ...BUSINESS_ERROR_MESSAGES,
  ...AUTH_ERROR_MESSAGES,
  ...VALIDATION_ERROR_MESSAGES,
  ...DATABASE_ERROR_MESSAGES
];

/**
 * 多语言错误消息工具类
 */
export class ErrorMessageUtils {
  /**
   * 根据错误码和语言获取错误消息
   * @param code 错误码
   * @param language 语言代码
   * @returns 错误消息
   */
  static getMessage(code: number, language: LanguageType): string {
    const errorMessage = ALL_ERROR_MESSAGES.find(msg => msg.code === code);
    if (!errorMessage) {
      return this.getDefaultMessage(language);
    }
    return errorMessage.messages[language] || errorMessage.messages[SUPPORTED_LANGUAGES.ZH_CN];
  }

  /**
   * 获取默认错误消息
   * @param language 语言代码
   * @returns 默认错误消息
   */
  static getDefaultMessage(language: LanguageType): string {
    const defaultMessages: Record<LanguageType, string> = {
      [SUPPORTED_LANGUAGES.ZH_CN]: '未知错误',
      [SUPPORTED_LANGUAGES.ZH_TW]: '未知錯誤',
      [SUPPORTED_LANGUAGES.EN_US]: 'Unknown error',
      [SUPPORTED_LANGUAGES.JA_JP]: '不明なエラー',
      [SUPPORTED_LANGUAGES.KO_KR]: '알 수 없는 오류',
      [SUPPORTED_LANGUAGES.FR_FR]: 'Erreur inconnue',
      [SUPPORTED_LANGUAGES.DE_DE]: 'Unbekannter Fehler',
      [SUPPORTED_LANGUAGES.ES_ES]: 'Error desconocido',
      [SUPPORTED_LANGUAGES.PT_BR]: 'Erro desconhecido',
      [SUPPORTED_LANGUAGES.RU_RU]: 'Неизвестная ошибка'
    };
    return defaultMessages[language] || defaultMessages[SUPPORTED_LANGUAGES.ZH_CN];
  }

  /**
   * 获取所有错误码
   * @returns 错误码列表
   */
  static getAllErrorCodes(): number[] {
    return ALL_ERROR_MESSAGES.map(msg => msg.code);
  }

  /**
   * 检查错误码是否存在
   * @param code 错误码
   * @returns 是否存在
   */
  static hasErrorCode(code: number): boolean {
    return ALL_ERROR_MESSAGES.some(msg => msg.code === code);
  }

  /**
   * 获取指定语言的所有错误消息
   * @param language 语言代码
   * @returns 错误消息映射
   */
  static getAllMessagesForLanguage(language: LanguageType): Record<number, string> {
    const messages: Record<number, string> = {};
    ALL_ERROR_MESSAGES.forEach(msg => {
      messages[msg.code] = msg.messages[language] || msg.messages[SUPPORTED_LANGUAGES.ZH_CN];
    });
    return messages;
  }
}

export default ErrorMessageUtils; 